import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'

const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000

})

request.interceptors.request.use(config => {
  // Do something before request is sent
  if (store.getters.token) {
    config.headers['X-Token'] = store.getters.token
  }
  return config
}, error => {
  // Do something with request error
  return Promise.reject(error)
})
request.interceptors.response.use(response => {
  // Do something before response is sent
  const { errno, errmsg, data } = response.data

  if (errno === 0) {
    return data
  } else if (errno === 9997) {
    Message({
      message: errmsg,
      type: 'error'
    })
    store.dispatch('user/logout')
    router.push('/login')
    return Promise.reject(errmsg)
  } else {
    Message({
      message: errmsg,
      type: 'error'
    })
    return Promise.reject(errmsg)
  }
}, error => {
  // Do something with response error
  //  console.log(error.code)
  if (error.code === 'ECONNABORTED') {
    Message.error('请求超时')
  }
  return Promise.reject(error)
})
export default request
